package com.summer.log.center.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.summer.log.center.model.Log;
import com.summer.log.center.model.LogSearchParam;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

@Service
public class LogServiceImpl implements LogService {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public AggregatedPage<Log> search(LogSearchParam param) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (param.getLevel() != null && !"ALL".equals(param.getLevel())) {
            boolQueryBuilder.must(QueryBuilders.queryStringQuery(param.getLevel()).field("level"));
        }
        if (CollUtil.isNotEmpty(param.getTimestamp())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("@timestamp")
                    .from(param.getTimestamp().get(0))
                    .to(param.getTimestamp().get(1))
                    .includeLower(true)
                    .includeUpper(true));
        }
        if (StrUtil.isNotBlank(param.getMessage())) {
            boolQueryBuilder.must(QueryBuilders.queryStringQuery(param.getMessage()).field("message"));
        }


        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withPageable(PageRequest.of(param.getPageNum()-1, param.getPageSize()))
                .withSort(SortBuilders.fieldSort("@timestamp").order(SortOrder.DESC))
                .build();

        AggregatedPage<Log> page = elasticsearchTemplate.queryForPage(searchQuery, Log.class);


        return page;
    }
}
